import '../utils/log.dart';

class BaseListModel<T> {
  int total;
  int pageSize;
  int pageNum;
  List<T> list;

  BaseListModel({
    required this.total,
    required this.pageSize,
    required this.pageNum,
    required this.list,
  });

  factory BaseListModel.fromJson(
      Map<String, dynamic> json, T Function(Map<String, dynamic>) fromJsonT) {
    return BaseListModel<T>(
      total: json['total'] ?? 0,
      pageSize: json['pageSize'] ?? 0,
      pageNum: json['pageNum'] ?? 0,
      list: (json['list'] as List<dynamic>)
          .map((item) {
            try {
              return fromJsonT(item as Map<String, dynamic>);
            } catch (e) {
              Log.e('列表数据转模型异常: $e');
              return null;
            }
          })
          .where((item) => item != null) // 过滤掉 null 项
          .cast<T>()
          .toList(),
    );
  }

  Map<String, dynamic> toJson(Map<String, dynamic> Function(T) toJsonT) {
    return {
      'total': total,
      'pageSize': pageSize,
      'pageNum': pageNum,
      'list': list.map((item) => toJsonT(item)).toList(),
    };
  }
}
